<?php

use Doctrine\DBAL\LockMode;
use Doctrine\ORM\OptimisticLockException;

class IndexController extends Zend_Controller_Action
{

    protected $_em;
    protected $doctrine;
    protected $_userRepository;
    protected $_productRepository;
    protected $_purchaseRepository;
    protected $_demoRepository;


    public function init()
    {
        $this->doctrine = Zend_Registry::get('doctrine');
        $this->_em      = $this->doctrine->getEntityManager();

        $this->_userRepository      = $this->_em->getRepository('\ZC\Entity\User');
        $this->_purchaseRepository  = $this->_em->getRepository('\ZC\Entity\Purchase');
        $this->_productRepository   = $this->_em->getRepository('\ZC\Entity\Product');
        $this->_demoRepository      = $this->_em->getRepository('\ZC\Entity\Demo');
        
    }

    public function indexAction()
    {
        $fname = 'Asif';
        $lname = 'Akter';

        $user = new ZC\Entity\User();
        
        $user->setFirstname($fname);
        $user->setLastname($lname);

        $this->_em->persist($user);
        $this->_em->flush();

        $purchaseOne = new \ZC\Entity\Purchase();

        $purchaseOne->setAmount(1200.5);
        $purchaseOne->setStoreName('mina bazar');
        $purchaseOne->setUser($user);

        $purchaseTwo = new \ZC\Entity\Purchase();

        $purchaseTwo->setAmount(1000);
        $purchaseTwo->setStoreName('Almas');
        $purchaseTwo->setUser($user);

        $user->addPurchases($purchaseOne);
        $user->addPurchases($purchaseTwo);

        $this->_em->persist($purchaseOne);
        $this->_em->persist($purchaseTwo);
        $this->_em->flush();

        
    }

    public function deleteAction()
    {
        $fetchedUser = new ZC\Entity\User();
        $fetchedUser = $this->_userRepository->findOneByFirstname('Asif');
        var_dump($fetchedUser->getLastname());

        $this->_userRepository->removeUser($fetchedUser->getId());
        $this->_em->flush();
    }

    public function insertAction()
    {
        $purchase = new \ZC\Entity\Purchase();
        $purchase = $this->_purchaseRepository->findOneById(2);

        $bodySpray = new \ZC\Entity\Product();

        $bodySpray->setName('Adidus');
        $bodySpray->setAmount(240);
        $bodySpray->addPurchases($purchase);

        $soap = new \ZC\Entity\Product();

        $soap->setName('Dove');
        $soap->setAmount(65);
        $soap->addPurchases($purchase);

        //$purchase = new \ZC\Entity\Purchase();
        //$purchase = $this->_purchaseRepository->findOneById(2);

        $purchase->addProducts($bodySpray);
        $purchase->addProducts($soap);

        $this->_em->persist($soap);
        $this->_em->persist($bodySpray);
        $this->_em->persist($purchase);
        $this->_em->flush();
    }

    public function queryAction()
    {
        //$query = $this->_em->createQuery('SELECT u FROM ZC\Entity\User u where u.lastname = ?1');//for 3 HYDRATIONS except HYDRATE_SINGLE_SCALAR
        //$query = $this->_em->createQuery('SELECT u.firstname FROM ZC\Entity\User u where u.lastname = ?1');
        //$query->setParameter(1, 'Akter');
        //$users = $query->getResult(Doctrine\ORM\Query::HYDRATE_OBJECT);
        //$users = $query->getResult(Doctrine\ORM\Query::HYDRATE_ARRAY);
        //$users = $query->getResult(Doctrine\ORM\Query::HYDRATE_SCALAR);
        //$users = $query->getResult(Doctrine\ORM\Query::HYDRATE_SINGLE_SCALAR);

        //var_dump($users[0]->getFirstname());//for HYDRATE_OBJECT
        //var_dump($users[0]['firstname']);   //for HYDRATE_ARRAY
        //var_dump($users[0]['u_firstname']);   //for HYDRATE_SCALAR
        //var_dump($users); //for HYDRATE_SINGLE_SCALAR

        $query = $this->_em->createQuery('SELECT u FROM ZC\Entity\User u');
        $iterableResult = $query->iterate();
        foreach ($iterableResult AS $row)
        {
            //print_r($row);
            echo $row[0]->getFirstname()." ".$row[0]->getLastname()."\n";
            echo " ";
            $this->_em->detach($row[0]);
        }
    }

    /**
     * @example chapter 10
     * @link http://www.doctrine-project.org/docs/orm/2.0/en/reference/events.html
     */

    public function testAction()
    {
        $demo = new \ZC\Entity\Demo();

        $demo->setValue('exciting');
        

        $tmp = new \ZC\Entity\Temp();
        $tmp->setTmpvalue('new');
        $tmp->setDemo($demo);

        $demo->setTemp($tmp);
        
        $this->_em->persist($demo);
        $this->_em->persist($tmp);
        //$this->_em->flush();
        //$this->_em->flush();//change will take place for doStuffOnPostPersist()

        $testValue = implode(PATH_SEPARATOR, array(realpath(APPLICATION_PATH . '/../library'),get_include_path(),)
                     );
        echo $testValue;
    }

    /**
     * @example chapter 9:Optimistic Locking
     * @link http://www.doctrine-project.org/docs/orm/2.0/en/reference/transactions-and-concurrency.html
     */
    public function lockAction()
    {
        $theEntityId = 1;
        $expectedVersion = 1;

        $entity = new \ZC\Entity\Demo();
        $entity = $this->_em->find('ZC\Entity\Demo', $theEntityId);

        try {
            // assert version
            $this->_em->lock($entity, LockMode::OPTIMISTIC, $expectedVersion);
            //$entity->setValue('locking');
            $this->_em->remove($entity);
            $this->_em->persist($entity);
            $this->_em->flush();

            //echo $entity->getValue();

        } catch(OptimisticLockException $e) {
            echo "Sorry, but someone else has already changed this entity. Please apply the changes again!";
        }
    }


}

